package com.bootcamp.mall.service.malluser;

import com.bootcamp.mall.dao.MallUserDao;
import com.bootcamp.mall.model.bo.malluser.UserSignupLoginBO;
import com.bootcamp.mall.model.bo.user.UpdatePwdBO;
import com.bootcamp.mall.model.vo.malluser.UserSignupLoginVO;
import com.bootcamp.mall.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

/**
 * @program: mall
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-12 15:15
 **/

public class MallUserServiceImpl implements MallUserService {
    @Override
    public UserSignupLoginVO signup(UserSignupLoginBO userBO) {
        // sqlsession,mapper,method,close,trycatch commit, rollback七联
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        MallUserDao mapper = sqlsession.getMapper(MallUserDao.class);
        try {
            // 插入bo并将id封装到bo中
            Integer affectRows = mapper.insertUser(userBO);
            System.out.println(affectRows);
            UserSignupLoginVO userVO = new UserSignupLoginVO();
            sqlsession.commit();
            // 封装为vo返回
            userVO.setCode(0);
            userVO.setUserId(userBO.getUserId());
            userVO.setToken(userBO.getNickname());
            userVO.setName(userBO.getNickname());
            return userVO;
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return null;
        } finally {
            sqlsession.close();
        }
    }

    @Override
    public UserSignupLoginVO login(UserSignupLoginBO userBO) {
        //sql查询四连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        MallUserDao mapper = sqlsession.getMapper(MallUserDao.class);
        // 查询nickname
        UserSignupLoginVO userVO = mapper.selectVOByLoginBO(userBO);
        // close
        sqlsession.close();

        if (userVO.getName() == null) {
            return null;
        }
        // 封装vo
        userVO.setCode(0);
        userVO.setToken(userVO.getName());
        return userVO;
    }

    @Override
    public Integer updatePwd(UpdatePwdBO updatePwdBO) {
        // 判断新密码合法性
        String newPwd = updatePwdBO.getNewPwd();

        if (newPwd == null || newPwd.length() < 8) {
            return -1;
        }
        if (!newPwd.equals(updatePwdBO.getComfirmPwd())) {
            return -2;
        }

        // sql更改7连
        SqlSession sqlsession = MyBatisUtil.getSqlsession();
        MallUserDao mapper = sqlsession.getMapper(MallUserDao.class);
        try {
            // 插入bo并将id封装到bo中
            Integer affectRows = mapper.updatePwdById(updatePwdBO);
            if (affectRows == 1) {
                return 0;
            } else {
                return -3;
            }
        } catch (Exception e) {
            e.printStackTrace();
            sqlsession.rollback();
            return -4;
        } finally {
            sqlsession.close();
        }

    }
}
